from django.shortcuts import render
from django.conf import settings
from QQLoginTool.QQtool import OAuthQQ


# Create your views here.
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from .serializers import OAuthQQUserSerializer
from .utils import generate_sign_openid, decode_sign_openid
from .models import OAuthQQUser


class OAuthQQLoginView(APIView):
    # 获取参数
    def get(self, request):
        state = request.query_params.get('state', '/')

        # 1.创建QQ对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state=state)
        # 2.获取QQ登陆扫码页面,扫码后得到Authorization Code
        login_url = oauth_qq.get_qq_url()

        # # 3.通过Authentication Code获取Access Token
        # access_token = oauth_qq.get_access_token(code)
        # # 4.通过Access Token 获取OpenID
        # openid = oauth_qq.get_open_id(access_token=access_token)

        # 返回qq登陆页面
        return Response({'auth_url': login_url})


class OAuthQQUserView(GenericAPIView):
    serializer_class = OAuthQQUserSerializer

    def get(self, request):

        # 获取参数code ,校验
        code = request.query_params.get('code')
        if not code:
            return Response('Authentication Code Lost')
        # 创建QQ对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state='/')
        # 通过Authentication Code获取Access Token

        access_token = oauth_qq.get_access_token(code)

        # 通过Access Token获取OpenID
        openid = oauth_qq.get_open_id(access_token)

        # return Response({'openid': openid})
        # 通过openid查询qq用户对象
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 初次授权
            sign_openid = generate_sign_openid(openid)

            return Response({
                'access_token': sign_openid,
            })
        else:
            # 非初次授权
            user = oauth_qq_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAY_LOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'user_name': user.username,
                'user_id': user.id
            })

    def post(self, request):
        # 获取参数
        dict_data = request.data

        # 创建序列化器
        serializer = self.get_serializer(data=dict_data)

        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        return Response({
            'token': token,
            'user_id': user.id,
            'username': user.username
        })





